<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\Filingcabinet as FilingcabinetModel;
use app\admin\common\ServiceResponse;
use app\common\service\CompleteNotificationService;
use think\facade\Db;

class Filingcabinet extends BaseService
{

    use ServiceResponse;

    protected $return;
    protected $validate;
    protected $model;
    public function __construct()
    {
        parent::__construct();
        $this->model = new FilingcabinetModel();
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-03-04 16:41:54
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field = 'all')
    {
        $res = $this->model->getEnum(strtoupper($field), [], 'label');
        return $this->success($res);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-03-04 16:54:40
     * @param [type] @required
     * @return Renderable
     */
    public function getList(int $page = 1, int $limit = 10, array $where = [], $field = "id,file_type,file_id,title,customer_id,order_id,order_type,creator,create_time,update_time")
    {
        try {

            $query =  $this->model->with(['images', 'customer', 'creator'])->where($where);
            $total = $query->count();

            if ($total <= 0) {
                $return['code'] = 0;
            } else {

                $orderIDArr = [];
                $orderWholesal = [];

                $list = $query
                    ->field($field)
                    ->page($page, $limit)
                    ->order('id desc')
                    ->select()
                    ->append(['file_type_value'])
                    ->each(function ($item) use (&$orderIDArr, &$orderWholesal) {  // 使用 use 关键字并传引用
                        if ($item->order_type == 'order') {
                            array_push($orderIDArr, $item->order_id);
                        } elseif ($item->order_type == 'wholesal') {
                            array_push($orderWholesal, $item->order_id);
                        }
                    })
                    ->toArray();

                if ($orderIDArr) {
                    $orderList = $this->model->name('order')->field('id,order_no')->whereIn('id', $orderIDArr)->select()->toArray();
                    $orderList = array_column($orderList, 'order_no', 'id');
                }
                if ($orderWholesal) {
                    $orderWholesalist = $this->model->name('order')->field('id,order_no')->whereIn('id', $orderWholesal)->select()->toArray();
                    $orderWholesalist = array_column($orderWholesalist, 'order_no', 'id');
                }

                foreach ($list as $key => $value) {
                    if ($value['order_type'] == 'order') {
                        $list[$key]['order_no'] = $orderList[$value['order_id']] ?? '';
                    } elseif ($value['order_type'] == 'wholesal') {
                        $list[$key]['order_no'] = $orderWholesalist[$value['order_id']] ?? '';
                    }
                }
                $return['code'] = 0;
                $return['data'] = ['list' => $list, 'total' => $total];
            }
        } catch (\Throwable $th) {
            $return['message'] = 'Failed to retrieve list. ' . $th->getMessage();
            $return['code'] = 500001;
        }
        return $return;
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-03-04 17:07:30
     * @param [type] @required
     * @return Renderable
     */
    public function create(array $data)
    {
        // 开始事务
        $this->model::startTrans();
        try {
            $res = null;

            // 检查是否符合更新条件
            if (!empty($data['order_id']) && !empty($data['order_type']) && in_array($data['file_type'], [10, 20])) {
                $order = $this->model->name('order')->where('id', $data['order_id'])->find();
                if (empty($order)) {
                    return ['code' => 500001, 'message' => '订单不存在'];
                }

                // 尝试更新记录
                $res = $this->model->where([
                    'order_id' => $data['order_id'],
                    'order_type' => $data['order_type'],
                    'file_type' => $data['file_type'],
                    'customer_id' => $data['customer_id']
                ])->update([
                    'file_id' => $data['file_id'],
                    'title' => $data['title'],
                    'update_time' => date('Y-m-d H:i:s')
                ]);

                if ($res) {
                    // 获取 ID 用于日志记录
                    $recordId = $this->model->where([
                        'order_id' => $data['order_id'],
                        'order_type' => $data['order_type'],
                        'file_type' => $data['file_type'],
                        'customer_id' => $data['customer_id']
                    ])->value('id');
                }
            }

            // 如果未更新成功，则创建新记录
            if (!$res) {
                $record = $this->model::create($data);
                $recordId = $record->id;
                $res = $record ? true : false;
            }

            if (20 == $data['file_type'] && !empty($data['order_id']) && !empty($data['order_type'])) {
                $this->model->name('order')->where('id', $data['order_id'])->update([
                    'contract_signing_status' => 1
                ]); // 更新合同签署状态为已签约
            }

            // 记录操作日志
            if ($res) {
                $this->logger->logOperation($data['order_id'], 'order', '订单-上传文件柜', '上传文件柜',1,'filingcabinet',$recordId);
                $this->model::commit(); // 提交事务

                if (20 == $data['file_type'] && !empty($data['order_id']) && !empty($data['order_type'])) {
                    $notificationService = new CompleteNotificationService();
                    $order = $this->model->name('order')->where('id', $data['order_id'])->find();
                    $customer = Db::name('customer')->where('id', $order['user_id'])->find();
                    $notificationService->send('contract_signing', $order->toArray(), [$customer['owner']]);
                }
                return ['code' => 0]; // 返回成功
            }

            // 如果失败，回滚事务
            $this->model::rollback();
            return ['code' => 500001, 'message' => '文件保存失败'];
        } catch (\Throwable $th) {
            $this->model::rollback(); // 发生异常时回滚
            return ['code' => 500001, 'message' => '服务器内部错误：' . $th->getMessage()];
        }
    }

    /**
     * @describe 删除文件柜记录
     * @author: jiang
     * @date: 2025-01-27
     * @param int $id 文件柜记录ID
     * @return array
     */
    public function delete($id)
    {
        try {
            // 开始事务
            $this->model::startTrans();

            // 查找要删除的记录
            $record = $this->model->find($id);
            if (!$record) {
                return ['code' => 100001, 'message' => '记录不存在'];
            }

            // 删除记录
            $result = $record->delete();
            if (!$result) {
                $this->model::rollback();
                return ['code' => 500001, 'message' => '删除失败'];
            }

            // 记录操作日志
            $this->logger->logOperation($id, 'filingcabinet', '文件柜', '删除文件柜记录');

            // 提交事务
            $this->model::commit();

            return ['code' => 0, 'message' => '删除成功'];

        } catch (\Throwable $th) {
            $this->model::rollback();
            return ['code' => 500001, 'message' => '服务器内部错误：' . $th->getMessage()];
        }
    }
}
